package org.jeecg.modules.meter.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.enums.meter.MeterTypeEnum;
import org.jeecg.model.meter.reqvo.MeterDayReportReqVo;
import org.jeecg.model.meter.resvo.MeterDayReportRespVo;
import org.jeecg.model.meter.resvo.MeterUseListRespVo;
import org.jeecg.model.meter.resvo.MeterUseReportRespVo;
import org.jeecg.modules.meter.service.IMeterOrderService;
import org.jeecg.modules.meter.service.IMeterService;
import org.jeecg.modules.meter.service.IMeterUseService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 仪表报表
 * @Author: liurui
 * @Date:   2020-11-26
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "仪表报表")
@RestController
@RequestMapping("/b/meter/dayReport")
public class MeterDayReportController {
    @Autowired
    private IMeterUseService meterUseService;

    @Autowired
    private IMeterOrderService meterOrderService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private IMeterService meterService;

    @AutoLog(value = "仪表使用量-报表信息")
    @ApiOperation(value = "仪表使用量-报表信息", notes = "仪表使用量-报表信息")
    @GetMapping(value = "/useReport")
    public Result<IPage<MeterUseReportRespVo>> useReport(MeterDayReportReqVo meterDayReportReqVo){
        log.info("仪表使用量-报表信息接受参数:{}",meterDayReportReqVo);
        Result<List<MeterUseReportRespVo>> result = new Result<List<MeterUseReportRespVo>>();
        if (meterDayReportReqVo.getSearchStartTime() == null){
            meterDayReportReqVo.setSearchStartTime(DateUtils.addDate(new Date(),-7));
        }
        if (meterDayReportReqVo.getSearchEndTime() == null || meterDayReportReqVo.getSearchEndTime().compareTo(new Date()) > 0){
            meterDayReportReqVo.setSearchEndTime(new Date());
        }
        List<MeterUseReportRespVo> electricityUseList = meterService.findGroupList(meterDayReportReqVo);
        Map<String,MeterUseReportRespVo> electricityUseMap = new LinkedHashMap<>();
        if (electricityUseList.size() > 0){
            //electricityUseMap = electricityUseList.stream().collect(Collectors.toMap(MeterDayReportRespVo::getCoverDate, Function.identity()));
        }
        return null;
    }
    @RequestMapping("queryUseCount")
    public Result<MeterUseListRespVo> queryUseCount(MeterUseListRespVo meterDayReportReqVo){
        Result<MeterUseListRespVo> result = new Result<>();
        MeterUseListRespVo meterUseCount = meterUseService.queryUseCount(meterDayReportReqVo);
        meterUseCount.setMeterCode("合计");
        meterUseCount.setMeterType("-");
        meterUseCount.setFloorName("-");
        meterUseCount.setRoomName("-");
        meterUseCount.setCustomerName("-");
        meterUseCount.setMonth(meterDayReportReqVo.getStartMonth()+"~"+meterDayReportReqVo.getEndMonth());
        result.setResult(meterUseCount);
        return result;
    }
    @AutoLog(value = "仪表使用量-列表查询")
    @ApiOperation(value = "仪表使用量-列表查询", notes = "仪表使用量-列表查询")
    @GetMapping(value = "/queryUseList")
    public Result<IPage<MeterUseListRespVo>> queryUseList(MeterUseListRespVo meterDayReportReqVo,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
                Result<IPage<MeterUseListRespVo>> result = new Result<>();
                Page<MeterUseListRespVo> page = new Page<>(pageNo, pageSize);
                List<MeterUseListRespVo> pageList = meterUseService.queryUseList(page, meterDayReportReqVo);
                for (MeterUseListRespVo meterUseListRespVo:pageList ){
                if (meterUseListRespVo.getUseAmount() == null){
                meterUseListRespVo.setUseAmount("0");
                }
                if (meterUseListRespVo.getPayAmount() == null){
                meterUseListRespVo.setPayAmount("0");
                }
                if (meterUseListRespVo.getUsed() == null){
                meterUseListRespVo.setUsed("0");
                }
                meterUseListRespVo.setMonth(meterDayReportReqVo.getStartMonth()+"~"+meterDayReportReqVo.getEndMonth());
                }
                page.setRecords(pageList);
                result.setResult(page);
                result.setSuccess(true);
                return result;
     }

    @AutoLog(value = "仪表日收款报表-列表查询")
    @ApiOperation(value = "仪表日收款报表-列表查询", notes = "仪表日收款报表-列表查询")
    @GetMapping(value = "/list")
    public Result<List<MeterDayReportRespVo>> queryPageList(MeterDayReportReqVo meterDayReportReqVo) {
        log.info("仪表日收款报表-列表查询接受参数:{}",meterDayReportReqVo);
        Result<List<MeterDayReportRespVo>> result = new Result<List<MeterDayReportRespVo>>();

        if (meterDayReportReqVo.getSearchStartTime() == null){
            meterDayReportReqVo.setSearchStartTime(DateUtils.getDateStart(new Date()));
        }
        if (meterDayReportReqVo.getSearchEndTime() == null || meterDayReportReqVo.getSearchEndTime().compareTo(new Date()) > 0){
            meterDayReportReqVo.setSearchEndTime(new Date());
        }
        //获取电表缴费统计
        meterDayReportReqVo.setMeterType(MeterTypeEnum.METER_TYPE_ELECTRICITY.getCode());
        List<MeterDayReportRespVo> electricityOrderList = meterOrderService.findGroupList(meterDayReportReqVo);
        //将列表转成 日期 - 数据对象格式  即 2020-01-01  - 电表统计对象
        // 目的:查询出来的结果可能某个日期没有数据,需要和整个查询日期期间比较将没有的日期找出来,设置一个空对象进去
        Map<String,MeterDayReportRespVo> electricityOrderMap = new LinkedHashMap<>();
        if (electricityOrderList.size() > 0){
            electricityOrderMap = electricityOrderList.stream().collect(Collectors.toMap(MeterDayReportRespVo::getCoverDate, Function.identity()));
        }
        //获取水表缴费统计
        meterDayReportReqVo.setMeterType(MeterTypeEnum.METER_TYPE_WATER.getCode());
        List<MeterDayReportRespVo> waterOrderList = meterOrderService.findGroupList(meterDayReportReqVo);
        //将列表转成 日期 - 数据对象格式  即 2020-01-01  - 水表统计对象
        Map<String,MeterDayReportRespVo> waterOrderMap = new LinkedHashMap<>();
        if (waterOrderList.size() > 0){
            waterOrderMap = waterOrderList.stream().collect(Collectors.toMap(MeterDayReportRespVo::getCoverDate, Function.identity()));
        }
        Set<String> allSetDate = new LinkedHashSet<>();
        // 目的:查询出来的结果可能某个日期没有数据,需要和整个查询日期期间比较将没有的日期找出来,设置一个空对象进去
        while (meterDayReportReqVo.getSearchEndTime().compareTo(meterDayReportReqVo.getSearchStartTime()) >= 0 ){
            allSetDate.add(DateUtils.date2Str(meterDayReportReqVo.getSearchStartTime(),DateUtils.date_sdf));
            meterDayReportReqVo.setSearchStartTime(DateUtils.addDate(meterDayReportReqVo.getSearchStartTime(),1));
        }
        List<MeterDayReportRespVo> allList = new LinkedList<>();
        Iterator<String> it = allSetDate.iterator();
        //合计
        MeterDayReportRespVo totalVo = new MeterDayReportRespVo("合计","-",null);
        while (it.hasNext()) {
            String tempDate = it.next();
            MeterDayReportRespVo electricityVo = electricityOrderMap.get(tempDate);
            if (electricityVo == null) {
                electricityVo = new MeterDayReportRespVo(meterDayReportReqVo.getProjectName(),"电表",tempDate);
            } else {
                electricityVo.setProjectName(meterDayReportReqVo.getProjectName());
            }
            //计算合计
            calculateTotal(totalVo, electricityVo);
            allList.add(electricityVo);
            //水表
            MeterDayReportRespVo waterVo = waterOrderMap.get(tempDate);
            if (waterVo == null) {
                waterVo = new MeterDayReportRespVo(meterDayReportReqVo.getProjectName(),"水表",tempDate);
            } else {
                waterVo.setProjectName(meterDayReportReqVo.getProjectName());
            }
            //计算合计
            calculateTotal(totalVo, waterVo);
            allList.add(waterVo);
        }
        allList.add(totalVo);
        result.setSuccess(true);
        result.setResult(allList);
        return result;
    }

    /**
     * 计算合计
     * @param totalVo
     * @param subVo
     */
    private void calculateTotal(MeterDayReportRespVo totalVo, MeterDayReportRespVo subVo) {
        totalVo.setXianJin(totalVo.getXianJin().add(subVo.getXianJin()));
        totalVo.setZhuanZhang(totalVo.getZhuanZhang().add(subVo.getZhuanZhang()));
        totalVo.setWeixinpayOffline(totalVo.getWeixinpayOffline().add(subVo.getWeixinpayOffline()));
        totalVo.setAlipayOffline(totalVo.getAlipayOffline().add(subVo.getAlipayOffline()));
        totalVo.setPos(totalVo.getPos().add(subVo.getPos()));
        totalVo.setWeixinpay(totalVo.getWeixinpay().add(subVo.getWeixinpay()));
        totalVo.setAlipay(totalVo.getAlipay().add(subVo.getAlipay()));
        totalVo.setSubTotal(totalVo.getSubTotal().add(subVo.getSubTotal()));
    }

    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(MeterUseListRespVo meterUseListRespVo, HttpServletRequest request, HttpServletResponse response) {
        LoginUser user = SsoUtil.getLoginUser();
        // Step.1 组装查询条件
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        meterUseListRespVo.setSqlMap( sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(), "p", meterUseListRespVo.getMenuPath(), null, meterUseListRespVo.getDepartIdEx()));
        List<MeterUseListRespVo> meterUseListRespVoIPage = meterUseService.queryUseList(null, meterUseListRespVo);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "仪表使用量" + DateUtils.date2Str(new Date(),DateUtils.yyyyMMdd));
        mv.addObject(NormalExcelConstants.CLASS, MeterUseListRespVo.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("仪表使用量", "导出人:"+user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, meterUseListRespVoIPage);
        return mv;
    }

}
